//
//  FoodDetailViewController.m
//  B
//
//  Created by lanou on 16/5/10.
//  Copyright © 2016年 裴启航. All rights reserved.
//

#import "FoodDetailViewController.h"
#import "HeaderView.h"
#import "CaloriesTableViewCell.h"
#import "CaloriesTwoTableViewCell.h"
#import "CaloriesModel.h"
#import "ElementsTableViewCell.h"
#import "FooterTableViewCell.h"

@interface FoodDetailViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) UITableView *allTableView;
@property (nonatomic, strong) NSDictionary *listDic;
@property (nonatomic, strong) HeaderView *headerView;
@property (nonatomic, strong) NSMutableArray *listArrs;
@property (nonatomic, strong) NSArray *elementsArrs;
@property (nonatomic, strong) NSMutableArray *allKeysArrs;



@end

@implementation FoodDetailViewController

- (NSMutableArray *)listArrs
{
    if (!_listArrs) {
        _listArrs = [NSMutableArray array];
    }
    return _listArrs;
}

- (NSDictionary *)listDic
{
    if (!_listDic) {
        _listDic = [NSDictionary dictionary];
    }
    return _listDic;
}

- (NSMutableArray *)allKeysArrs
{
    if (!_allKeysArrs) {
        _allKeysArrs = [NSMutableArray array];
    }
    return _allKeysArrs;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    NSLog(@"%@", self.code);
    self.elementsArrs = @[@"热量", @"蛋白质", @"脂肪", @"碳水化合物", @"膳食纤维素"];

    [self requestDetailData];
    
    
}

- (void)subviews
{
    
    self.headerView = [[NSBundle mainBundle] loadNibNamed:@"headerView" owner:self options:nil].firstObject;
    _headerView.frame = CGRectMake(20, 64 + 20, self.view.frame.size.width - 40, 70);
    _headerView.backgroundColor = [UIColor whiteColor];
    _headerView.nameLable.text = self.listDic[@"name"];
    _headerView.calorylable.text = [NSString stringWithFormat:@"%@千卡", self.listDic[@"calory"]];
    _headerView.weight.text = [NSString stringWithFormat:@"/每%@克", self.listDic[@"weight"]];
    id string = self.listDic[@"thumb_image_url"];
    if ([string isKindOfClass:[NSNull class]]) {
        //        NSLog(@"------");
        _headerView.imageView1.image = [UIImage imageNamed:@"imageDownloadFail"];
    } else {
        _headerView.imageView1.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:self.listDic[@"thumb_image_url"]]]];
    }
    _headerView.layer.shadowColor = [UIColor colorWithWhite:0.607 alpha:1.000].CGColor; //shadowColor阴影颜色
    _headerView.layer.shadowOffset = CGSizeMake(4,4); //shadowOffset阴影偏移,x向右偏移4，y向下偏移4，默认(0, -3),这个跟shadowRadius配合使用
    _headerView.layer.shadowOpacity = 0.8; //阴影透明度，默认0
    _headerView.layer.shadowRadius = 2; //阴影半径，默认3
    
    _headerView.imageView1.layer.masksToBounds = YES;
    _headerView.imageView1.layer.cornerRadius = 50 / 2.0f; //设置为图片宽度的一半出来为圆形
    _headerView.imageView1.layer.borderWidth = 3.0f; //边框宽度
    _headerView.imageView1.layer.borderColor = [[UIColor whiteColor] CGColor]; //边框颜色
    //    [_headerView.caloryButton setTitle:@"千卡" forState:(UIControlStateNormal)];
    //    [_headerView.kilojoulesButton setTitle:@"千焦" forState:(UIControlStateNormal)];
    
    [self.view addSubview:_headerView];
    
    self.allTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64 + self.headerView.frame.size.height + 20 + 15, self.view.frame.size.width, self.view.frame.size.height - 64 - self.headerView.frame.size.height - 20 - 15 - 10) style:(UITableViewStylePlain)];
    self.allTableView.delegate = self;
    self.allTableView.dataSource = self;
    [self.allTableView registerNib:[UINib nibWithNibName:@"CaloriesTableViewCell" bundle:nil] forCellReuseIdentifier:@"cell"];
    [self.allTableView registerNib:[UINib nibWithNibName:@"ElementsTableViewCell" bundle:nil] forCellReuseIdentifier:@"elementsCell"];
    [self.allTableView registerNib:[UINib nibWithNibName:@"CaloriesTwoTableViewCell" bundle:nil] forCellReuseIdentifier:@"cellTwo"];
    [self.allTableView registerNib:[UINib nibWithNibName:@"FooterTableViewCell" bundle:nil] forCellReuseIdentifier:@"footerView"];
    [self.view addSubview:self.allTableView];
    self.allTableView.bounces = NO;
    
    self.allKeysArrs = nil;
    [self.allKeysArrs addObject:self.listDic[@"ingredient"][@"calory"]];
    [self.allKeysArrs addObject:self.listDic[@"ingredient"][@"protein"]];
    [self.allKeysArrs addObject:self.listDic[@"ingredient"][@"fat"]];
    [self.allKeysArrs addObject:self.listDic[@"ingredient"][@"carbohydrate"]];
    [self.allKeysArrs addObject:self.listDic[@"ingredient"][@"fiber_dietary"]];

}

- (void)push
{
    
}

- (void)requestDetailData
{
    NSString *url = [NSString stringWithFormat:@"http://food.boohee.com/fb/v1/foods/%@", self.code];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager GET:url parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"%@", responseObject);
        self.listDic = responseObject;
        [self subviews];
        self.listArrs = nil;
        NSArray *array = responseObject[@"units"];
        
        if (array) {
            for (NSDictionary *dic in array) {
                CaloriesModel *mode = [[CaloriesModel alloc] init];
                [mode setValuesForKeysWithDictionary:dic];
                [self.listArrs addObject:mode];
            }
            [self.allTableView reloadData];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@", error);
    }];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if ([self.listDic[@"compare"] allKeys].count > 0) {
        return 4;
    }
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if ([self.listDic[@"compare"] allKeys].count > 0) {
        if (section == 1) {
            return self.listArrs.count;
        } else if (section == 2) {
            return self.elementsArrs.count + 1;
        }
        return 1;
    } else {
        if (section == 0) {
            return self.elementsArrs.count + 1;
        }
        return 1;
    }
    
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([self.listDic[@"compare"] allKeys].count > 0) {
        if (indexPath.section == 0) {
            return 85;
        } else if (indexPath.section == 3) {
            return 100;
        } else if (indexPath.section == 1 && indexPath.row == self.listArrs.count - 1) {
            return 40;
        } else if (indexPath.section == 2 && indexPath.row == self.elementsArrs.count) {
            return 40;
        }
        return 30;
    } else {
        if (indexPath.section == 0 && indexPath.row == self.elementsArrs.count) {
            return 40;
        } else if (indexPath.section == 1) {
            return 100;
        }
        return 30;
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if ([self.listDic[@"compare"] allKeys].count > 0) {
        if (indexPath.section == 0) {
            CaloriesTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
            cell.imageView1.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:self.listDic[@"compare"][@"target_image_url"]]]];
            cell.amount1Lable.text = [NSString stringWithFormat:@"× %@", self.listDic[@"compare"][@"amount1"]];
            cell.contentLable.text = [NSString stringWithFormat:@"%@%@%@ = %@%@%@", self.listDic[@"compare"][@"amount0"], self.listDic[@"compare"][@"unit0"], self.listDic[@"name"], self.listDic[@"compare"][@"amount1"], self.listDic[@"compare"][@"unit1"], self.listDic[@"compare"][@"target_name"]];
            return cell;
        }
        if (indexPath.section == 1) {
            CaloriesTwoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellTwo" forIndexPath:indexPath];
            CaloriesModel *model = self.listArrs[indexPath.row];
            cell.amountUnitLable.text = [NSString stringWithFormat:@"%@ %@", model.amount, model.unit];
            cell.weightLable.text = [NSString stringWithFormat:@"%@ 克", model.weight];
            cell.caloryLable.text = [NSString stringWithFormat:@"%@ 千卡", model.calory];
            return cell;
        } else if (indexPath.section == 2) {
            ElementsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"elementsCell" forIndexPath:indexPath ];
            if (indexPath.row == 0) {
                cell.elementsLable.text = @"营养元素";
                cell.elementsLable.textColor = [UIColor grayColor];
                cell.weightLable.text = @"每100克";
                cell.weightLable.textColor = [UIColor grayColor];
                cell.notLable.text = @"备注";
                cell.notLable.textColor = [UIColor grayColor];
            } else {
                cell.elementsLable.text = self.elementsArrs[indexPath.row - 1];
                if (indexPath.row == 1) {
                    cell.weightLable.text = [NSString stringWithFormat:@"%@千卡", self.allKeysArrs[indexPath.row - 1]];
                } else {
                    cell.weightLable.text = [NSString stringWithFormat:@"%@克", self.allKeysArrs[indexPath.row - 2]];
                }
                cell.weightLable.textAlignment = NSTextAlignmentRight;
            }
            return cell;
        } else {
            FooterTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"footerView" forIndexPath:indexPath];
            if ([[self.listDic[@"health_light"] stringValue] isEqualToString:@"1"]) {
                cell.imageView1.backgroundColor = [UIColor greenColor];
                cell.typeLable.text = @"推荐";
                cell.typeLable.textColor = [UIColor greenColor];
            } else if ([[self.listDic[@"health_light"] stringValue] isEqualToString:@"2"]) {
                cell.imageView1.backgroundColor = [UIColor colorWithRed:1.000 green:0.839 blue:0.242 alpha:1.000];
                cell.typeLable.text = @"适量";
                cell.typeLable.textColor = [UIColor colorWithRed:1.000 green:0.839 blue:0.242 alpha:1.000];
            } else {
                cell.imageView1.backgroundColor = [UIColor redColor];
                cell.typeLable.text = @"少吃";
                cell.typeLable.textColor = [UIColor redColor];
            }
            cell.imageView1.layer.masksToBounds = YES;
            cell.imageView1.layer.cornerRadius = 10 / 2.0f; //设置为图片宽度的一半出来为圆形
            cell.contentLable.text = self.listDic[@"appraise"];
            return cell;
        }

    } else {
         if (indexPath.section == 0) {
            ElementsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"elementsCell" forIndexPath:indexPath ];
            if (indexPath.row == 0) {
                cell.elementsLable.text = @"营养元素";
                cell.elementsLable.textColor = [UIColor grayColor];
                cell.weightLable.text = @"每100克";
                cell.weightLable.textColor = [UIColor grayColor];
                cell.notLable.text = @"备注";
                cell.notLable.textColor = [UIColor grayColor];
            } else {
                cell.elementsLable.text = self.elementsArrs[indexPath.row - 1];
                if (indexPath.row == 1) {
                    cell.weightLable.text = [NSString stringWithFormat:@"%@ 千卡", self.allKeysArrs[indexPath.row - 1]];
                } else {
                    cell.weightLable.text = [NSString stringWithFormat:@"%@ 克", self.allKeysArrs[indexPath.row - 2]];
                }
                cell.weightLable.textAlignment = NSTextAlignmentRight;
            }
            return cell;
        } else {
            FooterTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"footerView" forIndexPath:indexPath];
            if ([[self.listDic[@"health_light"] stringValue] isEqualToString:@"1"]) {
                cell.imageView1.backgroundColor = [UIColor greenColor];
                cell.typeLable.text = @"推荐";
                cell.typeLable.textColor = [UIColor greenColor];
            } else if ([[self.listDic[@"health_light"] stringValue] isEqualToString:@"2"]) {
                cell.imageView1.backgroundColor = [UIColor colorWithRed:1.000 green:0.839 blue:0.242 alpha:1.000];
                cell.typeLable.text = @"适量";
                cell.typeLable.textColor = [UIColor colorWithRed:1.000 green:0.839 blue:0.242 alpha:1.000];
            } else {
                cell.imageView1.backgroundColor = [UIColor redColor];
                cell.typeLable.text = @"少吃";
                cell.typeLable.textColor = [UIColor redColor];
            }
            cell.imageView1.layer.masksToBounds = YES;
            cell.imageView1.layer.cornerRadius = 10 / 2.0f; //设置为图片宽度的一半出来为圆形
            cell.contentLable.text = self.listDic[@"appraise"];
            return cell;
        }
        
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
